package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import static com.shanxia.codec.Decoder.*;

/**
 * S -> C
 * 服务器查询充电桩历史充电记录
 */
@Data
public class Cmd401 extends ProtocolDataBase {

    public static final int MIN_SIZE = 8;

    private int v1;
    private int v2;
    private int index;              // 查询记录起始索引

    public Cmd401(){
        super.setCmd(401);
    }

    public static Cmd401 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd401 cmd = new Cmd401();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        //数据域长度
        int len = dataField.length;
        if (len < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 4字节查询记录起始索引
        cmd.index = bytesToIntLittle(dataField, offset);
        return cmd;
    }

    @Override
    public byte[] getDataField() {
        byte[] data = new byte[MIN_SIZE];
        int offset = 0;
        getBytesAsUint16(data, offset, this.v1);
        offset += 2;
        getBytesAsUint16(data, offset, this.v2);
        offset += 2;
        intToBytesLittle(data, offset, this.index);
        return data;
    }
}
